<template>
  <div v-if="visible" class="ai-modal-overlay" @click.self="handleClose">
    <div class="ai-modal-container">
      <div class="ai-modal-header">
        <h3>🤖 AI分析 - SQL执行计划</h3>
        <button class="close-btn" @click="handleClose">&times;</button>
      </div>
      
      <div class="ai-modal-body">
        <div v-if="loading" class="loading">
          <div class="spinner"></div>
          <span>正在分析SQL执行计划...</span>
        </div>
        
        <div v-else-if="error" class="error-message">
          <span class="error-icon">⚠️</span>
          {{ error }}
        </div>
        
        <div v-else-if="analysisResult" class="analysis-container">
          <!-- 执行计划部分 -->
          <div class="execution-plan-section">
            <div class="section-header">
              <h4>📊 执行计划</h4>
              <span class="plan-count">{{ analysisResult.executionPlan.length }} 个步骤</span>
            </div>
            
            <div class="plan-table-wrapper">
              <table class="plan-table">
                <thead>
                  <tr>
                    <th class="col-id">ID</th>
                    <th class="col-select-type">选择类型</th>
                    <th class="col-table">表名</th>
                    <th class="col-type">连接类型</th>
                    <th class="col-key">使用索引</th>
                    <th class="col-rows">预估行数</th>
                    <th class="col-extra">额外信息</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(step, index) in analysisResult.executionPlan" :key="index">
                    <td class="col-id">{{ step.id || '-' }}</td>
                    <td class="col-select-type">{{ step.selectType || '-' }}</td>
                    <td class="col-table">{{ step.table || '-' }}</td>
                    <td class="col-type" :class="getTypeClass(step.type)">{{ step.type || '-' }}</td>
                    <td class="col-key" :class="getKeyClass(step.key)">{{ step.key || '-' }}</td>
                    <td class="col-rows" :class="getRowsClass(step.rows)">{{ formatRows(step.rows) }}</td>
                    <td class="col-extra">{{ step.extra || '-' }}</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
          
          <!-- AI分析结果部分 -->
          <div class="ai-analysis-section">
            <div class="section-header">
              <h4>🧠 AI分析结果</h4>
              <span class="analysis-badge">DeepSeek</span>
            </div>
            
            <div class="analysis-content">
              <pre class="analysis-text">{{ analysisResult.aiAnalysis }}</pre>
            </div>
          </div>
        </div>
        
        <div v-else class="no-data">
          <div class="no-data-icon">🔍</div>
          <div class="no-data-text">暂无分析结果</div>
          <div class="no-data-desc">请重新尝试分析</div>
        </div>
      </div>
      
      <div class="ai-modal-footer">
        <button class="btn btn-close" @click="handleClose">关闭</button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'AiAnalysisDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    loading: {
      type: Boolean,
      default: false
    },
    error: {
      type: String,
      default: null
    },
    analysisResult: {
      type: Object,
      default: null
    }
  },
  methods: {
    handleClose() {
      this.$emit('close')
    },
    
    // 格式化行数显示
    formatRows(rows) {
      if (!rows) return '-'
      if (rows >= 1000000) {
        return (rows / 1000000).toFixed(1) + 'M'
      }
      if (rows >= 1000) {
        return (rows / 1000).toFixed(1) + 'K'
      }
      return rows.toString()
    },
    
    // 获取连接类型的样式类
    getTypeClass(type) {
      if (!type) return ''
      const lowerType = type.toLowerCase()
      if (['const', 'system'].includes(lowerType)) return 'type-good'
      if (['eq_ref', 'ref', 'range'].includes(lowerType)) return 'type-ok'
      if (['index', 'all'].includes(lowerType)) return 'type-bad'
      return ''
    },
    
    // 获取索引的样式类
    getKeyClass(key) {
      if (!key || key === 'NULL') return 'key-none'
      return 'key-used'
    },
    
    // 获取行数的样式类
    getRowsClass(rows) {
      if (!rows) return ''
      if (rows <= 100) return 'rows-good'
      if (rows <= 10000) return 'rows-ok'
      return 'rows-bad'
    }
  },
  mounted() {
    // 添加ESC键关闭功能
    const handleEsc = (e) => {
      if (e.key === 'Escape' && this.visible) {
        this.handleClose()
      }
    }
    document.addEventListener('keydown', handleEsc)
    this.$once('hook:beforeDestroy', () => {
      document.removeEventListener('keydown', handleEsc)
    })
  }
}
</script>

<style scoped>
.ai-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
  backdrop-filter: blur(3px);
}

.ai-modal-container {
  background: white;
  border-radius: 12px;
  width: 95%;
  max-width: 1200px;
  max-height: 95vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  box-shadow: 0 25px 50px rgba(0, 0, 0, 0.2);
}

.ai-modal-header {
  padding: 20px 24px;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
  color: white;
}

.ai-modal-header h3 {
  margin: 0;
  font-size: 1.4em;
  font-weight: 600;
}

.close-btn {
  background: none;
  border: none;
  font-size: 28px;
  color: white;
  cursor: pointer;
  padding: 0;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 6px;
  transition: background 0.2s;
}

.close-btn:hover {
  background: rgba(255, 255, 255, 0.2);
}

.ai-modal-body {
  flex: 1;
  overflow-y: auto;
  padding: 0;
}

.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px;
  color: #6b7280;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #e5e7eb;
  border-top-color: #f59e0b;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 20px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.error-message {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 30px;
  background: #fee2e2;
  color: #dc2626;
  margin: 20px;
  border-radius: 8px;
  border: 1px solid #fecaca;
}

.error-icon {
  font-size: 24px;
}

.analysis-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.execution-plan-section {
  border-bottom: 2px solid #e5e7eb;
  background: #f8fafc;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: #f1f5f9;
  border-bottom: 1px solid #e2e8f0;
}

.section-header h4 {
  margin: 0;
  font-size: 1.1em;
  font-weight: 600;
  color: #374151;
}

.plan-count {
  background: #3b82f6;
  color: white;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.analysis-badge {
  background: #f59e0b;
  color: white;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.plan-table-wrapper {
  overflow-x: auto;
  padding: 0 24px 20px;
}

.plan-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 13px;
  min-width: 800px;
}

.plan-table th {
  background: #e2e8f0;
  color: #374151;
  font-weight: 600;
  padding: 12px 8px;
  text-align: left;
  border: 1px solid #cbd5e1;
  white-space: nowrap;
}

.plan-table td {
  padding: 10px 8px;
  border: 1px solid #e2e8f0;
  vertical-align: top;
  font-family: 'Courier New', monospace;
  font-size: 12px;
}

.plan-table tbody tr:hover {
  background: #f1f5f9;
}

/* 列宽控制 */
.col-id { width: 60px; }
.col-select-type { width: 100px; }
.col-table { width: 120px; }
.col-type { width: 100px; }
.col-key { width: 120px; }
.col-rows { width: 100px; }
.col-extra { width: 200px; }

/* 性能指示颜色 */
.type-good { background: #dcfce7; color: #166534; }
.type-ok { background: #fef3c7; color: #92400e; }
.type-bad { background: #fee2e2; color: #991b1b; }

.key-used { background: #dcfce7; color: #166534; }
.key-none { background: #fee2e2; color: #991b1b; }

.rows-good { background: #dcfce7; color: #166534; }
.rows-ok { background: #fef3c7; color: #92400e; }
.rows-bad { background: #fee2e2; color: #991b1b; }

.ai-analysis-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.analysis-content {
  flex: 1;
  overflow-y: auto;
  padding: 24px;
  background: #fefefe;
}

.analysis-text {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  font-size: 14px;
  line-height: 1.6;
  color: #374151;
  white-space: pre-wrap;
  word-wrap: break-word;
  margin: 0;
  background: none;
  border: none;
  padding: 0;
}

.no-data {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 20px;
  color: #9ca3af;
}

.no-data-icon {
  font-size: 64px;
  margin-bottom: 20px;
}

.no-data-text {
  font-size: 20px;
  font-weight: 500;
  color: #6b7280;
  margin-bottom: 8px;
}

.no-data-desc {
  font-size: 14px;
  color: #9ca3af;
}

.ai-modal-footer {
  padding: 16px 24px;
  border-top: 1px solid #e5e7eb;
  display: flex;
  justify-content: flex-end;
  background: #f9fafb;
}

.btn {
  padding: 10px 20px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  border: none;
}

.btn-close {
  background: #6b7280;
  color: white;
}

.btn-close:hover {
  background: #4b5563;
  transform: translateY(-1px);
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .ai-modal-container {
    width: 98%;
  }
  
  .analysis-container {
    flex-direction: column;
  }
  
  .plan-table {
    font-size: 11px;
  }
  
  .plan-table th,
  .plan-table td {
    padding: 8px 6px;
  }
}

@media (max-width: 768px) {
  .ai-modal-header {
    padding: 16px 20px;
  }
  
  .ai-modal-header h3 {
    font-size: 1.2em;
  }
  
  .section-header {
    padding: 12px 16px;
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .analysis-content {
    padding: 16px;
  }
  
  .analysis-text {
    font-size: 13px;
  }
}
</style>